﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>
		<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
		<title>Caching</title>
		<link type="text/css" rel="stylesheet" href="bootstrap.min.css" />
	</head>

	<body>

		<div class="document-contents">

			<h3>Introduction</h3>

			<p>ASP.NET Boilerplate provides an abstraction for caching. It internally uses this cache abstraction. While default 
implementation uses
				<a href="https://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache(v=vs.110).aspx?f=255&amp;MSPPError=-2147217396">
MemoryCache</a>, it can be implemented and changable for any other caching 
provider.</p>

			<h3>ICacheManager</h3>

			<p>Main interface for caching is <strong>ICacheManager</strong>. We can 
				<a href="/Pages/Documents/Dependency-Injection">inject</a> it and use it to get a cache. Example:</p>

			<pre lang="cs">public class TestAppService : ApplicationService
{
    private readonly ICacheManager _cacheManager;

    public TestAppService(ICacheManager cacheManager)
    {
        _cacheManager = cacheManager;
    }

    public Item GetItem(int id)
    {
        //Try to get from cache
        return _cacheManager
                .GetCache(&quot;MyCache&quot;)
                .Get(id.ToString(), () =&gt; GetFromDatabase(id)) as Item;
    }

    public Item GetFromDatabase(int id)
    {
        //... retrieve item from database
    }
}</pre>
			<p>In this sample, we're injecting <strong>ICacheManager</strong> and getting a 
cache named <strong>MyCache</strong>.</p>

			<div class="bs-callout bs-callout-warning">
				<h4>
					<strong>WARNING: </strong>GetCache Method</h4>
				<p>Do not use GetCache method in your constructor. This may dispose the 
	Cache if your class is transient.</p>
			</div>

			<h3>ICache</h3>

			<p>ICacheManager.<strong>GetCache</strong> method returns an <strong>ICache</strong>. 
A cache is singleton (per cache name). It is created first time it's 
requested, then returns always the same cache object. So, we can share same 
cache with same name in different classes (clients).</p>
			<p>In the sample code, we see simple usage of ICache.<strong>Get</strong> 
method. It has two arguments:</p>
			<ul>
				<li>
					<strong>key</strong>: A string unique key of an item in the cache.</li>
				<li>
					<strong>factory</strong>: An action which is called if there is no 
	item with the given key. Factory method should create and return the 
	actual item. This is not called if given key has present in the cache.</li>
			</ul>
			<p>ICache interface also has methods like <strong>GetOrDefault</strong>,
				<strong>Set</strong>, <strong>Remove</strong> and <strong>Clear</strong>. 
There are also <strong>async</strong> versions of all methods.</p>

			<h3>ITypedCache</h3>

			<p>
				<strong>ICache </strong>interface works <strong>string</strong> as key 
and <strong>object</strong> as value. <strong>ITypedCache</strong> is a 
wrapper to ICache to provide <strong>type safe</strong>, generic cache. To 
convert ICache to ITypedCache, we can use <strong>AsTyped</strong> extension method as shown 
below:</p>
			<pre lang="cs">ITypedCache&lt;int, Item&gt; myCache = _cacheManager.GetCache(&quot;MyCache&quot;)<strong>.AsTyped&lt;int, Item&gt;()</strong>;</pre>
			<p>Then we can use Get method without converting and casting code.</p>

			<h3>Configuration</h3>

			<p>Default cache expire time is 60 minutes. It's sliding. So, if you don't use 
an item in the cache for 60 minutes, it's automatically removed from the cache. 
You can configure it for all caches or for a specific cache.</p>
			<pre>//Configuration for all caches
Configuration.Caching.ConfigureAll(cache =&gt;
{
    cache.DefaultSlidingExpireTime = TimeSpan.FromHours(2);
});

//Configuration for a specific cache
Configuration.Caching.Configure(&quot;MyCache&quot;, cache =&gt;
{
    cache.DefaultSlidingExpireTime = TimeSpan.FromHours(8);
});</pre>
			<p>This code should be placed
				<a href="/Pages/Documents/Module-System#DocModulePreInit">
					<strong>PreInitialize</strong>
				</a> 
method of your module. With such a code, MyCache will have 8 hours expire time 
while all other caches will have 2 hours.</p>
			<p>Your configuration action is called once cache is first created (on 
first request). Configuration is not restricted to DefaultSlidingExpireTime 
only, since cache object is an ICache, you can use it's properties and methods 
freely configure and initialize it.</p>

		</div>

	</body>

</html>
